package com.parkinglot.controller;

import com.parkinglot.core.PayUtil;
import com.parkinglot.core.Result;
import com.parkinglot.parmeter.MonthRecordParm;
import com.parkinglot.parmeter.MonthVipParm;
import com.parkinglot.parmeter.OrderPayParm;
import com.parkinglot.pojo.*;
import com.parkinglot.service.*;
import com.parkinglot.util.DateUtils;
import com.parkinglot.util.HttpUrlutils;
import com.parkinglot.util.RedisUtil;
import com.parkinglot.vo.GaragequeryVo;
import com.parkinglot.vo.OrderqueryVo;
import com.parkinglot.vo.UserCarVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Slf4j
@ApiOperation(value = "微信请求支付接口")
public class WechatPayController {

    @Resource
    private PayUtil payUtil;
    @Resource
    private OrderService orderService;
    @Resource
    private HttpUrlutils httpUrlutils;
    @Resource
    private MonthbilRecordService monthbilRecordService;
    @Resource
    private GarageMonthConfigService garageMonthConfigService;
    @Resource
    private UserService userService;
    @Resource
    private WechatPayService wechatPayService;
    @Resource
    private GarageService garageService;


    private String appid = "wxf92e6814d9c36303";
    private String mchid = "1559378051";
    private String key = "401458FD86EF48488D087B7BF1BF848C";
    private String AppSecret = "adfe9eadd8e155cdb25ae498379b1952";
    private String url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";//统一下单接口路径
    private String zhifuurl = "https://wechatpay-api.gitbook.io/wechatpay-api-v3";

/*    @ApiOperation(value = "请求支付接口")
    @PostMapping("/wxPay")
    public Result wxPay(HttpServletRequest request, @RequestBody WeChatParm weChatParm) throws Exception {

        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", "wx9832ac19576d1e1b");
        paraMap.put("mch_id", mchid);
        // paraMap.put("description","tgrtrdtfdg");
        paraMap.put("nonce_str", PayUtil.generateNonceStr());
        paraMap.put("out_trade_no", String.valueOf(RandomsUtil.buildRandom()));//商品的订单号每次要唯一
        paraMap.put("openid", weChatParm.getOpenid());//oKEpW1veMHKLfaT4GttoIcoj_azo
        paraMap.put("total_fee", "100");//单位为分
        paraMap.put("spbill_create_ip", "123.12.12.123");
        paraMap.put("notify_url", "http://www.weixin.qq.com/wxpay/pay.php");// 此路径是微信服务器调用支付结果通知路径
        paraMap.put("trade_type", "JSAPI");
        paraMap.put("body", "测试微信支付");
        String sign = WXPayUtil.generateSignature(paraMap, "401458FD86EF48488D087B7BF1BF848C");
        paraMap.put("sign", sign);
        String xml = WXPayUtil.mapToXml(paraMap);
        System.out.println(xml);
        String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        Map<String, String> mapHeader = new HashMap<String, String>();
        mapHeader.put("Content-Type", "application/json;charset=utf-8");
        String xmlStr = HttpTools.post(unifiedorder_url, xml, mapHeader);
        log.debug("调取微信支付返回的值：" + xmlStr);
//以下内容是返回前端页面的json数据
        String mweb_url = "";//跳转链接
        if (xmlStr.indexOf("SUCCESS") != -1) {
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            map.put("out_trade_no", paraMap.get("out_trade_no").toString());
            log.debug(JSON.toJSONString(map));
            return Result.success(map);
        }
        return Result.failure("erro");
    }*/

    //这里是支付回调接口，微信支付成功后会自动调用
    @PostMapping(value = "/wxNotify")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("调用微信支付回调");
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        log.debug(sb.toString());
        //sb为微信返回的xml
        String resXml = "";
        //解析微信返回的xml串
        Map map = PayUtil.doXMLParse(sb.toString());

        String returnCode = (String) map.get("return_code");

        if ("SUCCESS".equals(returnCode)) {
            log.info("进入了回调，并修改支付状态");
            String oredernumber = map.get("out_trade_no").toString();
            System.out.println("oredernumber订单号:"+oredernumber+"-----------------------------");
            OrderqueryVo orderqueryVo = orderService.queryByordernum(oredernumber);
            if (orderqueryVo != null) {
                Order order = new Order();
                order.setPayStatus("1");
                order.setPayTime(DateUtils.getFormatDate(new Date()));
                order.setOrdernumber(orderqueryVo.getOrdernumber());
                order.setParkingCktime(DateUtils.getFormatDate(new Date()));
                orderService.updateOrder(order);
                if(orderqueryVo.getType()==1){

                    String tgurl = "http://192.168.3.205:8080/inPark/unlicensedInPark?carNumber=" + oredernumber + "&parkId=" + orderqueryVo.getGarageid();
                    Map<String, Object> maps = httpUrlutils.getresult(tgurl);
                }


                log.info("订单编号："+oredernumber+":openid:"+orderqueryVo.getUserid()+",支付金额："+orderqueryVo.getPayMoney()+",支付状态:"+orderqueryVo.getPayStatus());

            }

            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }


    @PostMapping("wechatpay")
    @ApiOperation(value = "小程序请求支付接口")//常规进出
    public Result wechatPay(OrderPayParm orderPayParm) throws Exception {

        if (RedisUtil.get("OrderPayParm") != null) return Result.failure("请勿重复支付");

        RedisUtil.set("OrderPayParm", orderPayParm, 1);

        Map<String, String> map=null;


        log.info(orderPayParm.toString());
        OrderqueryVo orderqueryVo1=null;

        //查询订单
        Order order = new Order();
        order.setUserid(orderPayParm.getUserid());
        order.setCarnumber(orderPayParm.getCarnumber());
        order.setGarageid(orderPayParm.getGarageid());
        OrderqueryVo orderqueryVo = orderService.queryOrder(order);//查询订单  获取订单的入场时间和出场时间
        orderqueryVo.setParkingCktime(DateUtils.getFormatDate(new Date()));
        if(orderqueryVo==null) return Result.success("没有这条记录");

        GaragequeryVo garagequeryVo = garageService.queryBygaragecode(orderPayParm.getGarageid());//查询停车场收费标准

        String firsttime=orderqueryVo.getParkingTime();
        String endtime=orderqueryVo.getParkingCktime();
        int hours = DateUtils.sjc(firsttime, endtime);//入场时间和出场时间的时间差

        if(orderPayParm.getEwmzt().equals("2")){
            Map<String,String>maps=wxyufukuan(orderPayParm);
            return Result.success(maps);
        }else {

            if (hours < 60) {
                order.setPayMoney(garagequeryVo.getBanhour());
                orderService.update(order);

            } else if (hours > 60) {
                BigDecimal money = garagequeryVo.getOnehour();
                BigDecimal banmoney=garagequeryVo.getBanhour();
                int xiaoshi=hours/60; //hours是分钟数  除60  换算小时
                int yushu=hours%60;  //取余数  余数大于30分钟  就加上半小时金额
                BigDecimal xiaoshis=BigDecimal.valueOf(xiaoshi);
                BigDecimal yushus=BigDecimal.valueOf(yushu);
                //    BigDecimal hour = BigDecimal.valueOf(hours);
                BigDecimal total = money.multiply(xiaoshis);
                if(yushu>30){
                total=total.add(money);
                }else if(yushu<30){
                    total=total.add(banmoney);
                }

                order.setPayMoney(total);
                orderService.update(order);

            }
            String money = String.valueOf(orderqueryVo.getPayMoney().multiply(new BigDecimal(100)).intValue());
            //String ordernumber,String openid,String paymoney
            String xmlStr = WechatPay.paiparm(orderqueryVo.getOrdernumber(), orderqueryVo.getUserid(), money, 0);
           map = WechatPay.issuccess(xmlStr);

        }


        return Result.success(map);
    }
    /**
     * 1.openid 车库id 车牌号 (月票针对用户和具体的车牌号)
     * 2.根据openid 和车库id查询订单记录
     * 3.计算月票结束时间  月票规则30天
     *
     * @return
     */
    @PostMapping("/monthVipPay")
    @ApiOperation(value = "小程序月票支付请求")
    public Result monthVip(@RequestBody MonthVipParm monthVipParm) throws Exception {
        if (RedisUtil.get("MonthVipParm") != null) return Result.failure("请勿重复支付");

        RedisUtil.set("MonthVipParm", monthVipParm, 1);
        if(monthVipParm.getCarnumber()==null)return Result.failure("车牌号不能为空");
        UserCarVo userCarVo=userService.checkcarnumber(monthVipParm.getGarageCode(),monthVipParm.getUserid(),monthVipParm.getCarnumber());
       if(!userCarVo.getCarnumber().equals(monthVipParm.getCarnumber()))return Result.failure("车牌号不正确");



/*        String appId = "wx9832ac19576d1e1b";
        String mch_id = "1604456142";
        String key = "401458FD86EF48488D087B7BF1BF848C";*/
        //查询月票价格
        GarageMonthConfig garageMonthConfig = garageMonthConfigService.queryAll(monthVipParm.getGarageCode());
        MonthRecordParm monthRecordParm = new MonthRecordParm();

        //生成月票订单
        monthRecordParm.setPayMoney(garageMonthConfig.getMonthvipmoney());//金额
        monthRecordParm.setMonthUserid(monthVipParm.getUserid());//openid
        monthRecordParm.setUserphone(monthVipParm.getUserphone());//手机号
        monthRecordParm.setGarageid(garageMonthConfig.getGarageCode());
        monthRecordParm.setCarnumber(monthVipParm.getCarnumber());
        MonthbilRecord monthbilRecord = monthbilRecordService.insertoverride(monthRecordParm);

       String xmstr= WechatPay.paiparm(monthbilRecord.getMonthOrder(),monthVipParm.getUserid(),String.valueOf(monthbilRecord.getPayMoney().multiply(new BigDecimal(100)).intValue()),1);
         Map<String,String>map=   WechatPay.issuccess(xmstr);
        //拼接下单地址参数
    /*    Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", WechatPay.getAppId());
        paraMap.put("mch_id", WechatPay.getMch_id());
        paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paraMap.put("out_trade_no", monthbilRecord.getMonthOrder());
        paraMap.put("openid", monthVipParm.getUserid());
        paraMap.put("total_fee", String.valueOf(monthbilRecord.getPayMoney().multiply(new BigDecimal(100)).intValue()));//单位为分
        paraMap.put("spbill_create_ip", "123.12.12.123");
        paraMap.put("notify_url", "http://47.104.250.83/parking/pay/wxmonthvipNotify");
        paraMap.put("trade_type", "JSAPI");
        paraMap.put("body", "测试微信支付");
        String sign = WXPayUtil.generateSignature(paraMap, key);
        paraMap.put("sign", sign);
        String xml = WXPayUtil.mapToXml(paraMap);
        String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        Map<String, String> mapHeader = new HashMap<String, String>();
        mapHeader.put("Content-Type", "application/json;charset=utf-8");
        String xmlStr = HttpTools.post(unifiedorder_url, xml, mapHeader);
        System.out.println("调取微信支付返回的值：" + xmlStr);
        if (xmlStr.indexOf("SUCCESS") != -1) {
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            Map<String, String> reData = new HashMap<>();
            reData.put("appId", appId);
            reData.put("nonceStr", map.get("nonce_str"));
            String newPackage = "prepay_id=" + map.get("prepay_id");
            reData.put("package", newPackage);
            reData.put("signType", "MD5");
            reData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
            String newSign = WXPayUtil.generateSignature(reData, key);
            map.put("paySign", newSign);
            map.put("timeStamp", reData.get("timeStamp"));
            return Result.success(map);
        }*/

        return Result.success(map);
    }



    @ApiOperation(value = "月票支付回调")
    @PostMapping(value = "/wxmonthvipNotify")
    public void wxmonthvipNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.debug("调用微信月票支付回调-------------------------------------------");
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        log.info(sb.toString());
        //sb为微信返回的xml
        String resXml = "";
        //解析微信返回的xml串
        Map map = PayUtil.doXMLParse(sb.toString());

        String returnCode = (String) map.get("return_code");

        if ("SUCCESS".equals(returnCode)) {
            log.info("判断succes为true，进入了回调，并修改支付状态");
            String oredernumber = map.get("out_trade_no").toString();
            log.info(oredernumber+":订单号输出出来了");
            MonthbilRecord monthbilRecord = null;
            monthbilRecord = monthbilRecordService.queryAllone(oredernumber);//根据订单查询订单
            log.info("monthbilRecord输出的值："+monthbilRecord.toString());
            if (monthbilRecord != null) {
                log.info("进入到判断中，monthbilRecord  !=   null");
                monthbilRecord.setMonthStartime(DateUtils.getFormatDate(new Date()));
                monthbilRecord.setMonthEndtime(DateUtils.plusDay2(30, monthbilRecord.getMonthStartime()));//月票结束时间
                monthbilRecord.setPayStatus("11");
                monthbilRecordService.update(monthbilRecord);
                User user=new User();
                user.setVipstatus(1);
                user.setUserid(monthbilRecord.getMonthUserid());
                userService.update(user);
                log.info("月票支付流程操作完成");
                String monthvipurl="http://192.168.3.237:8080/monthlyCard/handle";
                Map<String, Object> maps = httpUrlutils.getmonthvip(monthvipurl,monthbilRecord.getPayMoney().toString(),monthbilRecord.getMonthStartime(),monthbilRecord.getCarnumber(),monthbilRecord.getMonthEndtime(),monthbilRecord.getGarageid());
            }
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

    /**
     * 月票续费支付
     */
    @PostMapping("/monthrenew")
    @ApiOperation(value = "月票续费请求")
    public Result monthrenew(@RequestBody MonthVipParm monthVipParm) throws Exception {

        if (RedisUtil.get("MonthVipParm") != null) return Result.failure("请勿重复支付");

        RedisUtil.set("MonthVipParm", monthVipParm, 30);


        //查询月票价格
        GarageMonthConfig garageMonthConfig = garageMonthConfigService.queryAll(monthVipParm.getGarageCode());
        MonthRecordParm monthRecordParm = new MonthRecordParm();

        //生成订单
        monthRecordParm.setPayMoney(garageMonthConfig.getMonthvipmoney());//金额
        monthRecordParm.setMonthUserid(monthVipParm.getUserid());//openid
        monthRecordParm.setUserphone(monthVipParm.getUserphone());//手机号
        monthRecordParm.setGarageid(garageMonthConfig.getGarageCode());
        MonthbilRecord monthbilRecord = monthbilRecordService.insertoverride(monthRecordParm);

        // ordernumber, openid, paymoney, zt 0:正常出入 1月票支付回调 2月票续费回调
       String xmlStr=  WechatPay.paiparm(monthbilRecord.getMonthOrder(),monthVipParm.getUserid(),String.valueOf(monthbilRecord.getPayMoney().multiply(new BigDecimal(100)).intValue()),2);
        Map<String,String>map=WechatPay.issuccess(xmlStr);
        return Result.success(map);



    }




    @ApiOperation(value = "月票续费支付回调")
    @PostMapping(value = "/wxmonthrenenwNotify")
    public void wxmonthrenenwNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.debug("调用微信月票支付回调-------------------------------------------");
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        log.info(sb.toString());
        //sb为微信返回的xml
        String resXml = "";
        //解析微信返回的xml串
        Map map = PayUtil.doXMLParse(sb.toString());

        String returnCode = (String) map.get("return_code");

        if ("SUCCESS".equals(returnCode)) {
            log.info("进入了回调，并修改支付状态");
            String oredernumber = map.get("out_trade_no").toString();
            log.info(oredernumber+":订单号输出出来了");
            MonthbilRecord monthbilRecord = null;
            monthbilRecord = monthbilRecordService.queryAllone(oredernumber);//根据订单查询订单
            log.info("monthbilRecord输出的值："+monthbilRecord.toString());
            if (monthbilRecord != null) {
                log.info("进入到判断中，monthbilRecord  !=   null");
               // monthbilRecord.setMonthStartime(DateUtils.getFormatDate(new Date()));
                monthbilRecord.setMonthEndtime(DateUtils.plusDay2(30, monthbilRecord.getMonthStartime()));//月票结束时间
                monthbilRecord.setPayStatus("11");

                monthbilRecordService.update(monthbilRecord);
                User user=new User();
                user.setVipstatus(1);
                user.setUserid(monthbilRecord.getMonthUserid());
                userService.update(user);
                log.info("月票支付流程操作完成");
            }
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }



  /*  @ApiOperation(value = "预付款接口")
    @PostMapping(value = "/wxyufukuan")*/
    public Map<String,String> wxyufukuan(OrderPayParm orderPayParm)throws Exception{

        return wechatPayService.yufuuan(orderPayParm);
    }

    @ApiOperation(value = "预付款接口回调")
    @PostMapping(value = "/yufukuanNotify")
    public Result wxyufukuan(HttpServletRequest request, HttpServletResponse response)throws Exception{

        return Result.success(wechatPayService.yufukuanNotify(request,response));
    }


}
